<!DOCTYPE html>
<html>
<head>
    <title>Node.js Scrcpy投屏</title>
    <style>
        body { margin: 0; background: #1a1a1a; color: #fff; font-family: Arial, sans-serif; }
        #container { max-width: 1200px; margin: 0 auto; padding: 20px; }
        h1 { text-align: center; color: #4CAF50; }
        #video-wrapper { display: flex; justify-content: center; padding: 20px; }
        video { max-width: 100%; border: 2px solid #444; border-radius: 8px; }
        #status { text-align: center; margin-top: 20px; padding: 10px; background: #2a2a2a; border-radius: 4px; }
        #error { color: #f44336; background: #ffebee; padding: 10px; border-radius: 4px; margin-top: 10px; display: none; }
        #troubleshooting { margin-top: 20px; padding: 15px; background: #2a2a2a; border-radius: 4px; }
        h3 { color: #2196F3; }
        ul { text-align: left; display: inline-block; }
        li { margin-bottom: 5px; }
    </style>
</head>
<body>
    <div id="container">
        <h1>Node.js Scrcpy投屏</h1>
        <div id="video-wrapper">
            <video id="screen" autoplay controls></video>
        </div>
        <div id="status">
            连接状态: 等待连接...
            <div id="error"></div>
        </div>
        <div id="troubleshooting">
            <h3>常见问题排查</h3>
            <ul>
                <li>确保已安装scrcpy和ffmpeg并添加到系统环境变量</li>
                <li>确保安卓手机已连接并开启USB调试模式</li>
                <li>检查手机是否授权了USB调试权限</li>
                <li>尝试重启服务器和重新连接手机</li>
            </ul>
        </div>
    </div>

    <script>
        const ws = new WebSocket(`ws://${window.location.host}`);
        const mediaSource = new MediaSource();
        const video = document.getElementById('screen');
        const status = document.getElementById('status');
        const errorDiv = document.getElementById('error');
        
        video.src = URL.createObjectURL(mediaSource);

        let sourceBuffer;
        let bufferQueue = [];

        // 更新连接状态
        ws.onopen = () => {
            status.textContent = '连接状态: 已连接服务器';
            console.log('WebSocket已连接');
        };

        ws.onclose = () => {
            status.textContent = '连接状态: 连接已断开';
            showError('WebSocket连接已断开，请刷新页面重试');
            console.log('WebSocket已断开');
        };

        ws.onerror = (error) => {
            status.textContent = '连接状态: 连接错误';
            showError(`WebSocket连接错误: ${error}`);
            console.error('WebSocket错误:', error);
        };

        mediaSource.addEventListener('sourceopen', () => {
            try {
                sourceBuffer = mediaSource.addSourceBuffer('video/mp4; codecs="avc1.42E01E"');
                sourceBuffer.mode = 'sequence';
                
                // 处理缓冲队列中的数据
                sourceBuffer.addEventListener('updateend', () => {
                    if (bufferQueue.length > 0 && !sourceBuffer.updating) {
                        const nextBuffer = bufferQueue.shift();
                        sourceBuffer.appendBuffer(nextBuffer);
                    }
                });
                
                status.textContent = '连接状态: 准备接收视频流';
            } catch (e) {
                showError(`MediaSource初始化错误: ${e}`);
                console.error('MediaSource错误:', e);
            }
        });

        ws.onmessage = (event) => {
            // 检查是否是错误消息（文本格式）
            if (typeof event.data === 'string') {
                try {
                    const message = JSON.parse(event.data);
                    if (message.type === 'error') {
                        showError(`${message.source}错误: ${message.message}`);
                    }
                } catch (e) {
                    console.log('收到文本消息:', event.data);
                }
            } else if (sourceBuffer) {
                // 处理二进制视频数据
                if (sourceBuffer.updating) {
                    // 如果sourceBuffer正在更新，将数据加入队列
                    bufferQueue.push(new Uint8Array(event.data));
                } else {
                    try {
                        sourceBuffer.appendBuffer(new Uint8Array(event.data));
                    } catch (e) {
                        console.error('追加视频数据错误:', e);
                    }
                }
            }
        };

        // 显示错误信息
        function showError(message) {
            errorDiv.textContent = '错误: ' + message;
            errorDiv.style.display = 'block';
        }

        // 定期检查缓冲队列长度
        setInterval(() => {
            if (bufferQueue.length > 100) {
                // 如果队列过长，清空一部分以避免内存溢出
                bufferQueue = bufferQueue.slice(-50);
                console.warn('缓冲队列过长，已清理');
            }
        }, 5000);
    </script>
</body>
</html>
